package com.ruoyi.util;

import cn.hutool.core.io.resource.ClassPathResource;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

/**
 * 处理文件工具类
 */
public class HandleFileUtil {

    /**
     * 获取word模板
     * @param templatePath
     * @return
     */
    public static InputStream getWordTemplate(String templatePath) {
        ClassPathResource templateResource = new ClassPathResource(templatePath);
        // 指定word模板
        InputStream wordTemplate = templateResource.getStream();
        return wordTemplate;
    }

    /**
     * 设置模板参数并返回文件流
     * @param response
     * @param wordTemplate
     * @param finalMap
     */
    public static void writeToWord(HttpServletResponse response, InputStream wordTemplate, Map<String, Object> finalMap) {
        // 参数bind
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure build = Configure.builder().bind(policy, "workList").build();
        XWPFTemplate render = XWPFTemplate.compile(wordTemplate, build).render(finalMap);
        try {
            OutputStream out = response.getOutputStream();
            render.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置模板参数并返回pdf文件流
     * @param response
     * @param wordTemplate
     * @param finalMap
     */
    public static void writeToPdf(HttpServletResponse response, InputStream wordTemplate, Map<String, Object> finalMap) {
        // 设置响应内容类型为PDF
        response.setContentType("application/pdf");

        // 参数bind
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure build = Configure.builder().bind(policy, "workList").build();

        try {
            // 生成Word文档
            XWPFTemplate template = XWPFTemplate.compile(wordTemplate, build).render(finalMap);
            XWPFDocument document = template.getXWPFDocument();

            // 设置PDF选项
            PdfOptions options = PdfOptions.create();

            // 获取输出流
            OutputStream out = response.getOutputStream();

            // 转换为PDF并输出
            PdfConverter.getInstance().convert(document, out, options);

            // 关闭资源
            out.flush();
            out.close();
            document.close();
            template.close();

        } catch (Exception e) {
            e.printStackTrace();
            // 可以根据需要添加错误处理逻辑
        }
    }

}
